using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization; 
using System.IO;
using System.Xml;
using System.Text;
using System;


public class StatsHandler : MonoBehaviour {
	
	private static StatsHandler instance;
 
	public static StatsHandler Instance
	{
		get
		{
			if (instance == null)
			{
				instance = new GameObject("Stats").AddComponent<StatsHandler> ();
			}
 
			return instance;
		}
	}
	
 
	public void OnApplicationQuit ()
	{
		instance = null;
		
		exportSessionStats();
	}
	
	
	private string statsFilePath; 
	private List<LevelStats> listStats = new List<LevelStats>();
	
	private LevelStats currentLevelStats; 
	
	void Awake(){
		statsFilePath = Application.persistentDataPath+"/Stats/";
		FileInfo statsFile = new FileInfo(statsFilePath);
		statsFile.Directory.Create();

	}
	
	public void newLevel(string name){
		currentLevelStats = new LevelStats(name);
		currentLevelStats.ResTime = Mathf.RoundToInt(Time.time);
		listStats.Add(currentLevelStats);
	}
	
	public void exportSessionStats(){
		SessionStats session_data = new SessionStats(listStats);
		
		FileInfo f = new FileInfo(statsFilePath+session_data.Name+".xml");
		if(f.Exists) return;
		
     	string result = XmlUtils.SerializeSessionStats(session_data); 
		XmlUtils.CreateXML(result,statsFilePath+session_data.Name+".xml");
	}
	
	public void reset(){
		listStats.Clear();	
	}
	
	public void setTime(){
		if(currentLevelStats != null){
			currentLevelStats.ResTime = Mathf.RoundToInt(Time.time - currentLevelStats.ResTime);	
		}
	}
	
	public void addMove(){
		if(currentLevelStats != null){
			currentLevelStats.Moves++;	
		}
	}
	
	public void addUsedUndo(){
		if(currentLevelStats != null){
			currentLevelStats.UsedUndo++;	
		}
	}
	
	public void addCanceledUndo(){
		if(currentLevelStats != null){
			currentLevelStats.CanceledUndo++;	
		}
	}
	
	public void addState(){
		if(currentLevelStats != null){
			currentLevelStats.States++;	
		}
	}
	
	public void addUsedState(){
		if(currentLevelStats != null){
			currentLevelStats.UsedStates++;	
		}
	}
	
	public void addDeletedState(){
		if(currentLevelStats != null){
			currentLevelStats.DeletedStates++;	
		}
	}
	
	public void addHint(){
		if(currentLevelStats != null){
			currentLevelStats.Hints++;	
		}
	}
		
}
